import type {ReactNode} from "react";
import type {WaterfallItemProps as ItemProps} from "./Item";

import React, {useEffect, useState} from "react";

export interface ContainerProps {
    dataSource?: ItemProps[];
    renderItem?: (item: ItemProps, index: number) => ReactNode;
}

const Container = function (props: Readonly<ContainerProps>) {
    const {dataSource, renderItem} = props;

    const [items, setItem] = useState<ReactNode[]>([]);

    useEffect(() => {
        if (dataSource && dataSource.length > 0) {
            setItem(() => {
                return dataSource.map((item, index) => {
                    if (!renderItem) return null;

                    let _key: any;
                    if (!_key) {
                        _key = `waterfall-item-${index}`;
                    }
                    return <React.Fragment key={_key}>{renderItem(item, index)}</React.Fragment>;
                })
            });
        } else {
            setItem([]);
        }
        return () => setItem([]);
    }, [dataSource]);

    return (
        <section className={"relative flex flex-wrap overflow-hidden gap-2.5"}>
            {items}
        </section>
    )
}

export default Container;